import { Component, OnInit, OnDestroy, AfterViewInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SystemService } from 'app/service/system.service';
import { Bully, BullySubjectService } from 'app/shared/service';
import { BROWSER_BROADCAST, SYSTEM_EVENT } from 'app/app.constants';
import { Subscription } from 'rxjs';
import { fadeIn, fadeOut } from 'app/animations/simple-anim';
import { LoginService } from 'app/auth/login.service';
import { AuthService } from 'app/auth/auth.service';
import { NzTreeComponent } from 'ng-zorro-antd';
import { DataManagementService } from 'app/pages/data-management/data-management.services';
import { PublicService } from 'app/public/public.service';

export interface ZoneCheckBoxItem {
    id?: number;
    name?: string;
    checked?: boolean;
    disabled?: boolean;
}

@Component({
    selector: 'itmp-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.css'],
    animations: [fadeIn, fadeOut]
})
export class HeaderComponent implements OnInit, AfterViewInit, OnDestroy {
    get newMsg(): any[] {
        return this.systemMessage.filter(item => item.isNew);
    }

    get newAlarmMessage(): any[] {
        return this.alarmList.filter(item => item.isNew);
    }

    get newIncidentMessage(): any[] {
        return this.incidentList.filter(item => item.isNew);
    }

    gisAccess = false;
    openGisLoading = false;
    showMsgBox = false;
    systemMessage = [];
    alarmList = [];
    incidentList = [];
    defaultCheckedKeys = []; // tree
    defaultSelectedKeys = []; // tree
    defaultExpandedKeys = []; // tree
    zoneAssignment: ZoneCheckBoxItem[] = [];
    subscripions: Subscription[] = [];
    userName = localStorage.getItem('user_name');
    roleName = localStorage.getItem('roleName');
    isChangePwVisible = false;
    alarm_total = '';
    alert_total = '';
    ir_total = '';
    // router名字
    routerName = '';

    zoneSelectedAll = false;
    zoneIndeterminate = false;
    selectAllDisabled = false;

    isLoading = false;

    @ViewChild('nzTree') nzTree: NzTreeComponent;

    constructor(
        private router: Router,
        public systemService: SystemService,
        private bully: BullySubjectService,
        public ls: LoginService,
        private auth: AuthService,
        private DMService: DataManagementService,
        private pus: PublicService,
        private route: ActivatedRoute
    ) {
        // 语言服务
        this.systemService.langSet();

        // 设置时间
        this.systemService.timeSet();

        // 查看gis权限
        this.checkGisAccess();
    }

    getZoneIdListByUser() {
        const queryData = {
            condition: {
                userId: localStorage.getItem('user_id'),
                user_Name: localStorage.getItem('user_name'),
                user_Pwd: null,
                organization_Id: null,
                userRole_Id: null,
                createTime: {
                    startTime: null,
                    endTime: null
                },
                updateTime: {
                    startTime: null,
                    endTime: null
                }
            },
            pageNum: 1,
            pageSize: 999999
        };
        this.DMService.getAllUser(queryData).subscribe(res => {
            const userZone = (res.content.content && res.content.content.length && res.content.content[0].userZoneRel) || [];
            this.systemService.userZoneList = userZone.map(zone => ({
                id: zone.vnqn_zone_id,
                isTemp: zone.permanent !== 1
            }));
            const zonePermanentIds = userZone.filter(zone => zone.permanent === 1).map(zone => zone.vnqn_zone_id);
            if (zonePermanentIds.length === this.zoneAssignment.length) {
                this.selectAllDisabled = true;
            }
            const zoneIds = userZone.map(zone => zone.vnqn_zone_id);
            this.zoneAssignment.forEach(item => {
                if (zoneIds.includes(item.id)) {
                    item.checked = true;
                    const f = userZone.find(zone => zone.vnqn_zone_id === item.id);
                    item.disabled = f ? f.permanent === 1 : false; // 永久权限的禁用
                }
            });
            this.zoneCheckedStatusSync();
        });
    }

    checkGisAccess() {
        const roleId = localStorage.getItem('role_id');
        this.auth.getAccessRightByRoleId(roleId).subscribe(res => {
            if (res['code'] === '000000') {
                this.gisAccess = res['data'].some(role => role.rightName === 'GIS');
                if (this.gisAccess) {
                    this.openGIS();
                }
            }
        });
    }

    handleChangePwCancel(param: boolean) {
        this.isChangePwVisible = false;
    }

    openGIS() {
        this.openGisLoading = true;
        const url = `${location.origin}/#/gis`;
        window.open(url);

        setTimeout(() => (this.openGisLoading = false), 5000);
    }

    login() {
        this.router.navigate(['/login']);
    }

    // 发送CCM登出状态的消息
    ccmlogOut() {
        this.ls.logOut();
    }

    private _clearMsg(data) {
        if (data.length > 50) {
            data.length = 50;
        }
    }

    ngOnInit() {
        this.getNewMessageNumber();
        this.getZoneData();
        // this.getZoneIdListByUser();
        let arr = this.router.url.split('/');
        this.routerName = arr[2];
        // console.log(this.routerName,"数组");
    }

    getNewMessageNumber() {
        // const subscriptionAlert = this.bully.getSubject().subscribe(res => {
        //     if (res['type'] === SYSTEM_EVENT.ALERT_EVENT) {
        //         if (res['data']) {
        //             const data = res['data'];
        //             data.time = Date.now();
        //             data.isNew = true;
        //             // 当长度大于50条时随机删除一个消息
        //             this._clearMsg(this.systemMessage);
        //             this.systemMessage = [res['data'], ...this.systemMessage];
        //         }
        //     }
        // });
        const subscriptionAlert = this.bully.getSubject().subscribe(res => {
            if (res['type'] === SYSTEM_EVENT.ALERT_TOTAL) {
                if (res.data >= 100) {
                    this.alert_total = '99+';
                } else {
                    this.alert_total = res.data;
                }
                // if (res['data']) {
                //     const data = res['data'];
                //     data.time = Date.now();
                //     data.isNew = true;
                //     this._clearMsg(this.systemMessage);
                //     this.systemMessage = [res['data'], ...this.systemMessage];
                // }
            }
        });
        // const subscriptionAlarm = this.bully.getSubject().subscribe(res => {
        //     if (res['type'] === SYSTEM_EVENT.ALARM_EVENT) {
        //         if (res['data']) {
        //             const data = res['data'];
        //             data.time = Date.now();
        //             data.isNew = true;
        //             // 当长度大于50条时随机删除一个消息
        //             this._clearMsg(this.alarmList);
        //             this.alarmList = [res['data'], ...this.alarmList];
        //         }
        //     }
        // });
        const subscriptionAlarm = this.bully.getSubject().subscribe(res => {
            if (res['type'] === SYSTEM_EVENT.ALARM_TOTAL) {
                if (res.data >= 100) {
                    this.alarm_total = '99+';
                } else {
                    this.alarm_total = res.data;
                }
                // if (res['data']) {
                //     const data = res['data'];
                //     data.time = Date.now();
                //     data.isNew = true;
                //     // 当长度大于50条时随机删除一个消息
                //     this._clearMsg(this.alarmList);
                //     this.alarmList = [res['data'], ...this.alarmList];
                // }
            }
        });
        const subscriptionIncident = this.bully.getSubject().subscribe(res => {
            if (res['type'] === SYSTEM_EVENT.INCIDENT_EVENT) {
                if (res.data >= 100) {
                    this.ir_total = '99+';
                } else {
                    this.ir_total = res.data;
                }
                // if (res['data']) {
                //     const data = res['data'];
                //     data.time = Date.now();
                //     data.isNew = true;
                //     // 当长度大于50条时随机删除一个消息
                //     this._clearMsg(this.incidentList);
                //     this.incidentList = [res['data'], ...this.incidentList];
                // }
            }
        });
        this.subscripions.push(subscriptionAlert, subscriptionAlarm, subscriptionIncident);
    }

    goToTrafficAlert() {
        this.router.navigate(['/ccm/traffic-management/traffic-alert-page']);
    }

    goToIncidentRecord() {
        this.router.navigate(['/ccm/traffic-management/incident-record']);
    }

    goToEquipmentAlarmList() {
        this.router.navigate(['/ccm/equipment-management/equipment-alarm']);
    }

    ngOnDestroy(): void {
        this.subscripions.forEach(item => {
            item.unsubscribe();
        });
    }

    ngAfterViewInit() {
        setTimeout(() => this.systemService.timeSet());
    }

    getZoneData() {
        this.pus.optionsList.forEach(ele => {
            const temp: ZoneCheckBoxItem = {};
            if (ele.category === 'zone') {
                temp.name = ele.name;
                temp.id = +ele.value;
                temp.checked = false;
                temp.disabled = false;

                this.zoneAssignment.push(temp);
            }
        });
        this.zoneAssignment.sort((a, b) => a.id - b.id);
        this.getZoneIdListByUser();
    }

    /**
     * 更新用户zone
     * @param data 区分是否批量操作
     */
    updateUserZone(data?) {
        const userId = localStorage.getItem('user_id');
        let queryData = `userId=${userId}`;
        if (data) {
            queryData += `&zoneId=${data.id}&selected=${data.checked ? 1 : 0}`;
        } else {
            if (this.zoneSelectedAll) {
                const checkIds = this.zoneAssignment
                    .filter(zone => !zone.disabled && zone.checked)
                    .map(zone => zone.id)
                    .join(',');
                queryData += `&zoneId=${checkIds}&selected=1`;
            } else {
                queryData += `&zoneId=&selected=0`;
            }
        }
        this.isLoading = true;
        this.auth.updateUserZone(queryData).subscribe(
            res => {
                this.isLoading = false;
                if (res.code === '000000') {
                    this.postZoneMsg();
                }
            },
            err => {
                this.isLoading = false;
            }
        );
    }

    postZoneMsg() {
        const bully: Bully = {
            type: SYSTEM_EVENT.ZONE_CHANGE_EVENT,
            data: this.systemService.userZoneList
        };
        BROWSER_BROADCAST.postMessage(bully);
        this.bully.setSubject(bully);
    }

    selectAllZone(e: boolean) {
        this.zoneAssignment.forEach(zone => !zone.disabled && (zone.checked = e));
        this.zoneIndeterminate = !this.zoneSelectedAll && this.zoneAssignment.some(zone => zone.checked);
        this.systemService.userZoneList = this.zoneAssignment.filter(z => z.checked).map(z => ({
            id: z.id,
            isTemp: !z.disabled
        }));
        this.updateUserZone();
    }

    zoneCheckedStatusSync(data?) {
        this.zoneSelectedAll = !!this.zoneAssignment.length && this.zoneAssignment.every(zone => zone.checked);
        this.zoneIndeterminate = !this.zoneSelectedAll && this.zoneAssignment.some(zone => zone.checked);
        this.systemService.userZoneList = this.zoneAssignment.filter(z => z.checked).map(z => ({
            id: z.id,
            isTemp: !z.disabled
        }));
        if (data) {
            this.updateUserZone(data);
        } else {
            this.postZoneMsg();
        }
    }
}
